interface LockedFile {
  name: string;
  content: ArrayBuffer;
  timestamp: number;
}

class IndexedDBManager {
  private dbName = 'boxComparisonDB';
  private storeName = 'lockedFiles';
  private version = 1;

  private async openDB(): Promise<IDBDatabase> {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open(this.dbName, this.version);

      request.onerror = () => reject(request.error);
      request.onsuccess = () => resolve(request.result);

      request.onupgradeneeded = (event) => {
        const db = (event.target as IDBOpenDBRequest).result;
        if (!db.objectStoreNames.contains(this.storeName)) {
          db.createObjectStore(this.storeName, { keyPath: 'name' });
        }
      };
    });
  }

  async saveFile(file: File): Promise<void> {
    // 首先读取文件内容
    const fileContent = await new Promise<ArrayBuffer>((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result as ArrayBuffer);
      reader.onerror = () => reject(reader.error);
      reader.readAsArrayBuffer(file);
    });

    // 然后打开数据库并保存
    const db = await this.openDB();
    return new Promise((resolve, reject) => {
      const transaction = db.transaction([this.storeName], 'readwrite');
      const store = transaction.objectStore(this.storeName);
      
      const lockedFile: LockedFile = {
        name: file.name,
        content: fileContent,
        timestamp: Date.now()
      };
      
      const request = store.put(lockedFile);
      request.onsuccess = () => resolve();
      request.onerror = () => reject(request.error);
      
      transaction.oncomplete = () => {
        db.close();
      };
      
      transaction.onerror = () => {
        reject(transaction.error);
      };
    });
  }

  async getFile(): Promise<File | null> {
    const db = await this.openDB();
    return new Promise((resolve, reject) => {
      const transaction = db.transaction([this.storeName], 'readonly');
      const store = transaction.objectStore(this.storeName);
      
      const request = store.getAll();
      request.onsuccess = () => {
        const files = request.result;
        if (files.length > 0) {
          const latestFile = files.reduce((latest, current) => 
            current.timestamp > latest.timestamp ? current : latest
          );
          
          const blob = new Blob([latestFile.content], { type: 'model/gltf-binary' });
          const file = new File([blob], latestFile.name, { type: 'model/gltf-binary' });
          resolve(file);
        } else {
          resolve(null);
        }
      };
      
      request.onerror = () => reject(request.error);
      
      transaction.oncomplete = () => {
        db.close();
      };
      
      transaction.onerror = () => {
        reject(transaction.error);
      };
    });
  }

  async removeFile(): Promise<void> {
    const db = await this.openDB();
    return new Promise((resolve, reject) => {
      const transaction = db.transaction([this.storeName], 'readwrite');
      const store = transaction.objectStore(this.storeName);
      
      const request = store.clear();
      request.onsuccess = () => resolve();
      request.onerror = () => reject(request.error);
      
      transaction.oncomplete = () => {
        db.close();
      };
      
      transaction.onerror = () => {
        reject(transaction.error);
      };
    });
  }
}

export const indexedDBManager = new IndexedDBManager(); 